package org.thread.test05.syn.demo01;

import java.util.Random;

/**
 * @author CSY
 * @date 2025 - 03 - 11
 */
public class MyRunnable implements Runnable {

    /**
     * 总票数
     */
    private Integer ticketCount;

    //字符串常量
//    private String lock = "";
    //private static Object lock = new Object();
    private Class<?> lock = Object.class;

    public MyRunnable() {}

    public MyRunnable(Integer ticketCount) {
        this.ticketCount = ticketCount;
    }

    @Override
    public void run() {
        //要注意锁的临界区范围 - 否则别的线程没有机会进来
//        synchronized (Object.class) {
        while (true) {
            synchronized (lock) {
                Integer sellCount = new Random().nextInt(1, 10);

                if (ticketCount == 0) {
                    System.out.println(Thread.currentThread().getName() + "没票了，停止售票");
                    break;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (sellCount <= ticketCount) {
                    ticketCount -= sellCount;
                    System.out.println(Thread.currentThread().getName() + "成功出售" + sellCount + "张票，剩余：" + ticketCount);
                } else {
                    sellCount = ticketCount;
                }
            }
        }
    }
}
